package org.zjx.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUtil {
    public static void saveXmlToFile(String xmlString, String filePath) {
        // 创建文件对象
        File file = new File(filePath);
//        if (!file.exists()) {file.mkdir();}

        // 使用 BufferedWriter 来写入内容
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            // 写入xmlString到文件
            writer.write(xmlString);
            System.out.println("XML has been successfully saved to " + filePath);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("An error occurred while saving the XML to the file.");
        }
    }

    public static void saveXmlToFile2(String xmlString, String filePath) {
        // 创建文件对象
        File file = new File(filePath);

        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8));
            // 写入xmlString到文件
            writer.write(xmlString);
            System.out.println("XML has been successfully saved to " + filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 保存 BufferedImage 到文件，支持 PNG 和 JPEG 格式
    public static void saveImage(BufferedImage image, String filePath, String png) {
        // 创建文件输出流
        File file = new File(filePath);
        String extension = getFileExtension(filePath).toLowerCase();

        try {
            // 根据文件扩展名选择合适的格式
            if ("png".equals(extension)) {
                ImageIO.write(image, "PNG", file);
            } else if ("jpg".equals(extension) || "jpeg".equals(extension)) {
                ImageIO.write(image, "JPEG", file);
            } else {
                throw new IllegalArgumentException("Unsupported image format: " + extension);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 从文件读取 BufferedImage
    public static BufferedImage loadImage(String filePath) throws IOException {
        File file = new File(filePath);
        return ImageIO.read(file);
    }

    // 保存文本内容到文件
    public static void saveFile(String content, String filePath) throws IOException {
        Path path = Paths.get(filePath);
        Files.write(path, content.getBytes());
    }

    // 读取文件内容为字符串
    public static String readFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        return new String(Files.readAllBytes(path));
    }

    // 获取文件扩展名
    private static String getFileExtension(String filePath) {
        int dotIndex = filePath.lastIndexOf('.');
        if (dotIndex == -1) {
            return "";
        }
        return filePath.substring(dotIndex + 1);
    }

    /**
     * 检查指定路径的文件是否存在
     * @param filePath 文件路径
     * @return 如果文件存在返回 true，否则返回 false
     */
    public static boolean fileExists(String filePath) {
        File file = new File(filePath);
        return file.exists() && file.isFile();
    }

    //检查文件是否可以被访问（未被占用）
    public static boolean isFileLocked(File file) {
        try {
            RandomAccessFile stream = new RandomAccessFile(file, "rw");
            stream.close();
            return false;  // 文件没有被占用
        } catch (IOException e) {
            return true;   // 文件被占用
        }
    }

}
